<template>
  <div class="container">
    <div class="head">
      <div>
        <a-select
          v-model:value="selectedClass"
          placeholder="请选择班级"
          style="width: 300px"
          @change="selectClass"
          :field-names="{ label: 'className', value: 'classId' }"
          :options="classOptions"
        >
          <template #option="{ classId, className }">
            <div class="class-option">
              {{ className }}
              <a-button
                type="dashed"
                @click.stop="showDeleteClassConfirm(classId, className)"
                class="confirmButton"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
              </a-button>
            </div>
          </template>
          <template #dropdownRender="{ menuNode: menu }">
            <v-nodes :vnodes="menu" />
            <a-divider style="margin: 4px 0" />
            <a-space style="padding: 4px 8px">
              <a-input ref="inputRef" v-model:value="newClassName" placeholder="输入班级名称" />
              <a-button type="text" @click="addClass(newClassName)" :loading="addClassLoading">
                <template #icon>
                  <plus-outlined />
                </template>
                添加班级
              </a-button>
            </a-space>
          </template>
        </a-select>
      </div>

      <div style="float: right; display: flex; justify-content: space-around; width: 25%">
        <a-button type="primary" :disabled="!selectedClass" @click="showAddStudent"
          >添加学生</a-button
        >
        <a-button type="primary" danger :disabled="!hasSelected" @click="showDeleteStudentConfirm()"
          >批量删除</a-button
        >
        <a-button type="primary" :disabled="!hasSelected" @click="visibleMoveStudent = true"
          >批量调动</a-button
        >
      </div>
    </div>
    <div class="body">
      <div style="padding-top: 10px; width: 20%; border-right: 1px solid rgba(5, 5, 5, 0.06)">
        <div style="display: flex; justify-content: space-between; padding: 0 10px">
          <span style="margin: 5px 5px; font-size: 16px; font-weight: bold">小组</span>
          <a-button type="link" @click="toOpenAddTeamModal">
            <template #icon>
              <PlusCircleOutlined />
            </template>
          </a-button>
        </div>

        <a-modal v-model:open="visibleAddTeam" title="添加小组" @ok="addTeam">
          <a-input v-model:value="newTeamName" placeholder="输入小组名称" />
        </a-modal>
        <div>
          <a-menu
            style="height: 65vh; border: 0px; overflow-y: auto"
            v-model:selectedKeys="selectedTeam"
            theme="light"
          >
            <a-menu-item :key="null" @click="selectTeam(null)">
              <span> <TeamOutlined /> 全部学生</span>
            </a-menu-item>

            <a-menu-item
              v-for="team in teamOptions"
              :key="team.teamId"
              @click="selectTeam(team.teamId)"
            >
              <div style="display: flex; justify-content: space-between">
                <span>
                  <TeamOutlined />
                  {{ team.teamName }}
                </span>

                <div>
                  <a-button
                    type="dashed"
                    @click.stop="showDeleteTeamConfirm(team)"
                    class="confirmButton"
                  >
                    <template #icon> <DeleteOutlined /> </template
                  ></a-button>
                </div>
              </div>
            </a-menu-item>
          </a-menu>
        </div>
      </div>

      <!-- 筛选 -->
      <div style="width: 80%">
        <a-form
          class="filter"
          ref="formRef"
          :model="formState"
          autocomplete="off"
          :label-col="labelCol"
        >
          <div class="filter-box">
            <div class="filter-options">
              <a-form-item label="学生名称" name="userName">
                <a-input v-model:value="formState.userName" placeholder="输入学生" allow-clear />
              </a-form-item>
              <a-form-item label="学生学号" name="studentId">
                <a-input v-model:value="formState.studentId" placeholder="输入学号" allow-clear />
              </a-form-item>
              <a-form-item label="分组状态" name="type">
                <a-select ref="select" v-model:value="formState.haveTeam" style="width: 120px">
                  <a-select-option :value="undefined">全部</a-select-option>
                  <a-select-option :value="1">已分组</a-select-option>
                  <a-select-option :value="0">未分组</a-select-option>
                </a-select>
              </a-form-item>
            </div>

            <div class="filter-buttons">
              <a-button
                type="primary"
                :disabled="!(hasSelected && selectedTeam[0] != null)"
                @click="setTeamLeader()"
                >设为组长</a-button
              >
              <a-button type="primary" @click="findClassStudents()">
                <template #icon> <SearchOutlined /> </template>查询</a-button
              >
            </div>
          </div>
        </a-form>

        <a-table
          style="padding: 5px; height: 80%"
          :pagination="false"
          :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="studentList"
          :loading="tableLoading"
          rowKey="userId"
          :scroll="{ y: 'calc(78vh - 200px)' }"
        >
          <template #bodyCell="{ record, column, text }">
            <template v-if="column.dataIndex === 'teamLeadingId'">
              <a-tag v-if="record.teamId == null" color="default">未分组</a-tag>
              <a-tag v-else-if="record.userId == record.teamLeaderId" color="green">组长</a-tag>
              <a-tag v-else color="blue">组员</a-tag>
            </template>
          </template>
        </a-table>
        <a-pagination
          v-model:current="current"
          v-model:page-size="pageSizeRef"
          :total="total"
          show-size-changer
          class="pagination"
        />
      </div>
    </div>
  </div>
  <contextHolder />
  <AddStudentModal
    v-model:model-visible="visibleAddStudent"
    :class-id="selectedClass"
    @confirm="findClassStudents()"
  />

  <MoveStudentModal
    v-model:model-visible="visibleMoveStudent"
    :classId="selectedClass"
    :teams="teamOptions"
    :students="state.selectedRowKeys"
    @confirm="findClassStudents()"
  ></MoveStudentModal>
</template>
<script lang="ts" setup>
import { useStore } from 'vuex';
import { message, Modal } from 'ant-design-vue';
import ClassDao from '@/daos/class_dao';
import UserDao from '@/daos/user_dao';
import TeamDao from '@/daos/team_dao';
import MoveStudentModal from './MoveStudentModal.vue';
import AddStudentModal from './AddStudentModal.vue';
const store = useStore();
const [modal, contextHolder] = Modal.useModal();
const classDao = new ClassDao();
const userDao = new UserDao();
const teamDao = new TeamDao();

//窗口开关
const visibleAddTeam = ref<boolean>(false);
const visibleAddStudent = ref<boolean>(false);
const visibleImportStudent = ref<boolean>(false);
const visibleMoveStudent = ref<boolean>(false);

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes;
  }
});

//加载状态
const addClassLoading = ref(false);
//获取课程id
const courseId = store.getters.courseId;

//班级和小组选项存储对象
const classOptions = ref([]);
const teamOptions = ref([]);

//班级选中对象
const selectedClass = ref(null);
//小组选中对象
const selectedTeam = ref([]);

//添加班级函数
const newClassName = ref();
const addClass = (className) => {
  if (className == '' || className == null) {
    message.info('班级名称不能为空');
  } else {
    classDao
      .addClass(courseId, className)
      .then((result) => {
        message.success(result.data.msg);
        newClassName.value = '';
        findClass();
      })
      .catch((error) => {
        console.error('添加班级错误 addClass', error);
      });
  }
};
//删除班级函数
const deleteClass = (classId) => {
  classDao
    .deleteClass(classId)
    .then((result) => {
      message.success(result.data.msg);
      findClass();
      selectedClass.value = undefined;
    })
    .catch((error) => {
      console.error('删除班级失败 deleteClass', error);
    });
};
//删除班级内的学生函数
const deleteClassStudent = () => {
  classDao
    .deleteClassStudentRef(selectedClass.value, state.selectedRowKeys)
    .then((result) => {
      message.success(result.data.msg);
      findClassStudents();
    })
    .catch((error) => {
      console.error('删除班级内的同学失败', error);
    });
};
//选择小组后 获取学生数据
const selectTeam = (teamId) => {
  if (teamId == null) {
    selectedTeam.value = [null];
  } else {
    selectedTeam.value = [teamId];
  }
  findClassStudents();
};
const setTeamLeader = () => {
  if (state.selectedRowKeys.length > 1) {
    message.info('小组组长只能有一位');
  } else {
    teamDao
      .setTeamLeader(selectedTeam.value[0], state.selectedRowKeys[0])
      .then((result) => {
        message.success(result.data.msg);
        findClassStudents();
      })
      .catch((error) => {
        console.error('修改小组组长失败', error);
      });
  }
};
//打开新增小组窗口
const toOpenAddTeamModal = () => {
  if (selectedClass.value == null) {
    message.info('请先选择班级');
  } else {
    visibleAddTeam.value = true;
  }
};
//添加小组
const newTeamName = ref('');
const addTeam = () => {
  if (newTeamName.value == '') {
    message.info('小组名称不能未空');
  } else {
    teamDao
      .addTeam(selectedClass.value, newTeamName.value)
      .then(async (result) => {
        message.success(result.data.msg);
        await findClass();
        selectClass(selectedClass.value);
        visibleAddTeam.value = false;
        newTeamName.value = '';
      })
      .catch((error) => {
        visibleAddTeam.value = false;
      });
  }
};
//删除小组
const deleteTeam = (teamId) => {
  teamDao.deleteTeam(teamId).then(async (result) => {
    message.success(result.data.msg);
    await findClass();
    selectClass(selectedClass.value);
  });
};
//删除小组时的气泡确认框
const showDeleteTeamConfirm = (team) => {
  modal.confirm({
    title: '确认删除' + team.teamName,
    content: '此操作会删除此小组相关的所有内容（包括上传的的成果与安排的任务）',
    okText: '删除',
    okType: 'danger',
    maskClosable: true,
    cancelText: '取消',
    width: 800,
    getContainer: () => document.body,

    bodyStyle: {
      // height: 'auto', // 高度
    },
    onOk() {
      deleteTeam(team.teamId);
    }
  });
};

//删除班级时的气泡确认框
const showDeleteClassConfirm = (classId, className) => {
  modal.confirm({
    title: '确认删除' + className,
    content: '此操作会删除此班级相关的所有内容（包括班级内的所有小组及其成果与安排的任务）',
    okText: '删除',
    maskClosable: true,
    okType: 'danger',
    zIndex: 1050,
    cancelText: '取消',
    width: 800,
    bodyStyle: {
      // height: '150px', // 高度
    },
    onOk() {
      deleteClass(classId);
    },
    onCancel() {}
  });
};
//删除学生时的气泡确认框
const showDeleteStudentConfirm = () => {
  modal.confirm({
    title: '确认删除',
    content: '确认删除学生吗？',
    okText: '删除',
    maskClosable: true,
    okType: 'danger',
    zIndex: 1050,
    cancelText: '取消',
    width: 800,
    bodyStyle: {
      // height: '150px', // 高度
    },
    onOk() {
      deleteClassStudent();
    },
    onCancel() {}
  });
};
const showAddStudent = () => {
  visibleAddStudent.value = true;
};

//筛选输入框存储对象
const formState = reactive({
  userName: '',
  studentId: undefined,
  haveTeam: null
});
//筛选标签宽度
const labelCol = { style: { width: '90px' } };
//表格加载选项
const tableLoading = ref(false);
//表格数据源
const studentList = ref([]);
//表格列表
const columns = [
  {
    title: '姓名',
    dataIndex: 'userName',
    align: 'center'
  },
  {
    title: '学号',
    dataIndex: 'studentId',
    align: 'center'
  },
  {
    title: '小组',
    dataIndex: 'teamName',
    align: 'center'
  },
  {
    title: '身份',
    dataIndex: 'teamLeadingId',
    align: 'center'
  }
];
//表格多选存储参数
const state = reactive<{
  selectedRowKeys: number[];
}>({
  selectedRowKeys: []
});
const onSelectChange = (selectedRowKeys: []) => {
  state.selectedRowKeys = selectedRowKeys;
};
//计算选中的学生数量是否大于0
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//分页参数
const current = ref(1);
const pageSizeRef = ref(10);
const total = ref();

//获取班级信息
const findClass = () => {
  return classDao.findClassByCourseId(courseId).then((result) => {
    classOptions.value = result.data.data; // 直接替换整个数组
  });
};
//选择班级后获取小组信息
const selectClass = (value) => {
  state.selectedRowKeys = [];
  teamOptions.value = classOptions.value.find((item) => item.classId == value).teamList;
};
//获取学生数据
const findClassStudents = () => {
  tableLoading.value = true;
  userDao
    .findClassStudents(
      selectedClass.value,
      selectedTeam.value[0],
      formState.studentId,
      formState.userName,
      formState.haveTeam,
      current.value,
      pageSizeRef.value
    )
    .then((result) => {
      console.log(result);

      studentList.value = result.data.data.rows;
      total.value = result.data.data.totalCount;
      tableLoading.value = false;
    })
    .catch((error) => {
      tableLoading.value = false;
    });
};
findClass();
watch(
  () => selectedClass.value,
  () => {
    selectedTeam.value = [null];
    findClassStudents();
  }
);
watch(
  () => selectedTeam.value,
  () => {
    state.selectedRowKeys = [];
  }
);
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  padding: 1%;
  height: 100%;
  min-width: 1280px;
  overflow: auto;
}

.head {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 1.5%;
  margin-bottom: 1%;
  height: 10%;
  width: 100%;
  min-height: 75px;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid lightgray;
  border-radius: 10px;
  background-color: #fff;
  overflow: auto;
}

.body {
  display: flex;
  flex-direction: row;
  padding: 0.5%;
  height: 90%;
  width: 100%;
  min-height: 540px;

  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid lightgray;
  border-radius: 10px;
  background-color: #fff;
  overflow: auto;
}

/*删除按钮样式*/
.confirmButton {
  background-color: transparent;
  border: none;
}

.filter {
  padding: 5px;
  display: flex;
  justify-content: space-between;
  height: 10%;
}

.filter-box {
  width: 100%;
  display: flex;
  padding: 0 15px;
  justify-content: space-between;
}

.filter-options {
  display: flex;
  width: 80%;
  flex-wrap: wrap;
}

.filter-buttons {
  display: flex;
  width: 20%;
  justify-content: space-around;
}
.pagination {
  height: 9%;
  text-align: center;
  bottom: 0%;
  margin-top: 1%;
}
</style>
